package cn.zwx.service;

import cn.zwx.IDGen;
import cn.zwx.common.Result;
import cn.zwx.common.SnowflakeConstant;
import cn.zwx.exception.InitException;
import cn.zwx.snowflake.SnowflakeIDGenImpl;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  SnowflakeService init
 *  @author zhangwenxue
 */
public class SnowflakeService {
    private Logger logger = LoggerFactory.getLogger(SnowflakeService.class);

    private IDGen idGen;


    public SnowflakeService(String zkPath,int port,Integer sessionTimeoutMs,Integer connectionTimeoutMs) throws InitException {
            Preconditions.checkNotNull(zkPath,"zookeeper path can not be null");
            Preconditions.checkNotNull(port,"zookeeper port  can not be null");
            if (sessionTimeoutMs <= 0L){
                sessionTimeoutMs = SnowflakeConstant.DEFAULT_SESSION_TIMEOUT;
            }
            if (connectionTimeoutMs <= 0L){
                connectionTimeoutMs = SnowflakeConstant.DEFAULT_CONNECTION_TIMEOUT;
            }
            idGen = new SnowflakeIDGenImpl(zkPath, port,sessionTimeoutMs,connectionTimeoutMs);
            if(idGen.init()) {
                logger.info("Snowflake Service Init Successfully");
            } else {
                throw new InitException("Snowflake Service Init Fail");
            }
    }

    public Result getId(String key) {
        return idGen.get(key);
    }
}
